package com.gitee.feizns.webtemplate.commons.web;

import com.gitee.feizns.webtemplate.commons.utils.date.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.convert.converter.Converter;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.sql.Date;

/**
 * @author feizns
 * @since 2019/5/10
 */
@Configuration
@EnableConfigurationProperties(MvcConfigProperties.class)
public class MvcAutoConfiguration implements WebMvcConfigurer {

    @Autowired
    private MvcConfigProperties properties;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        CORSProperties[] mappings = properties.getCORSMappings();
        if ( mappings != null ) {
            for (CORSProperties mapping : mappings) {
                registry.addMapping(mapping.getPathPattern())
                        .allowedOrigins(mapping.getAllowedOrigins())
                        .allowedMethods(mapping.getAllowedMethods())
                        .allowedHeaders(mapping.getAllowedHeaders());
            }
        }
    }

    @Override
    public Validator getValidator() {
        LocalValidatorFactoryBean validatorFactoryBean = new LocalValidatorFactoryBean();
        validatorFactoryBean.setValidationMessageSource(validateMessageSource());
        return validatorFactoryBean;
    }

    private MessageSource validateMessageSource() {
        ReloadableResourceBundleMessageSource result = new ReloadableResourceBundleMessageSource();
        result.setBasenames(properties.getValidateNames());
        return result;
    }

    @ConditionalOnProperty("mvc.config.sql-date-pattern")
    @Bean
    public Converter<String, Date> sqlDateConverter() {
        return new Converter<String, Date>() {
            @Override
            public Date convert(String source) {
                for (String pattern : properties.getSqlDatePattern()) {
                    Date date = DateUtils.parse(source, pattern);
                    if ( date != null )
                        return date;
                }
                return null;
            }
        };
    }

}
